//
//  Yahoo_Quote_WEB.m
//  MacStockApp
//
//  Created by 英傑 翁 on 12/3/9.
//  Copyright (c) 2012年 翁英傑. All rights reserved.
//

#import "Yahoo_Quote_WEB.h"
#import "CommonFunction.h"
#import "GBTableColumnHeader.h"
#import "GBTableColumnHeader_basicSqlite.h"
#import "GBTableColumnHeader_quote.h"
#import "GBTableColumnHeader_2Row3Row.h"
#import "GBTableColumnHeader_node.h" 
#import "GBTableColumnHeader_position.h"  
#import "GBTableColumnHeader_position_bottom_sumaverage.h"  
#import "GBTableColumnHeader_Indicator.h"  
#import "GBTableColumnHeader_signal.h"  
#import "GBTableColumnHeader_ObjectOtherKey.h"  
#import "GBall.h"

@implementation Yahoo_Quote_WEB
@synthesize delgeate;
- (id)init_WithURL:(NSURL*)url; {
	
    if(self=[super init])
	{
        
        targetURL= url  ;
        [targetURL retain];
    }
	
	return self;
}

//標記：建立執行緒 3.執行緒內的啟動- 在 addOperation 後面執行

- (void)main 
{ 
    NSLog(@"main_Start");
    
    
    //3.Header Field 欺騙bloomberg在User-Agent
    
    
    NSURL* url = targetURL;
    NSString *userAgent = Yahoo_web_User_Agent;
    NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:url]
                                    autorelease];
    [request setValue:userAgent forHTTPHeaderField:@"User-Agent"];
    //以下可以欺騙yahoo
    //[request setValue:@"vendor=\"fff\";" forHTTPHeaderField:@"X-Client-Info"];    
    
    NSURLResponse* response = nil;
    NSError* error = nil;
    NSData* data = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&response
                                                     error:&error];    
    
    NSString* aStr;
	aStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    NSArray *csvLines = [aStr  componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
    [aStr release];
    NSString *line  ;    
    NSArray *pdata ;  
    NSMutableArray *outarray=[[NSMutableArray alloc] init];    
    
    //1.建構報價資料陣列
    for (int i=0; i<[csvLines count]-1; i++) {
        line = (NSString *)[csvLines objectAtIndex:i];
        if (![line isEqualToString:@""]) {
           
                      
            line=[line stringByReplacingOccurrencesOfString:@"\"" withString:@"" ];
            //NSLog(@"%i line=%@",i,line); 
            pdata = [line componentsSeparatedByString:@","]   ;   
           
            
            if ([pdata count]>=11) {
               
                 NSMutableDictionary *tem_dic=[[NSMutableDictionary alloc] init];                 
                               
                //1.下面資料是yahoo,bloomberg 共同有的報價資料
                NSString *code_s= [[pdata objectAtIndex:0] stringByReplacingOccurrencesOfString:@"\"" withString:@"" ]  ;
                
                NSString *ds= [pdata objectAtIndex:5]  ;
                NSString *ts= [pdata objectAtIndex:6]  ;
                                
                NSDate *datetime_dt= [self yahoo_date_time_convert_to_NSDate:ds 
                                                                       times:ts 
                                                                        code:code_s];  
                
                double d_open;                
                double d_close;
                double d_high;
                double d_low;
                d_close= [[pdata objectAtIndex:2] doubleValue];
                if ([[pdata objectAtIndex:1] doubleValue]==0) {
                    d_open=d_close;
                }
                else {
                    d_open=[[pdata objectAtIndex:1] doubleValue];
                }
                if ([[pdata objectAtIndex:3] doubleValue]==0) {
                    d_high=d_close;
                }
                else {
                    d_high=[[pdata objectAtIndex:3] doubleValue];
                }                
                if ([[pdata objectAtIndex:4] doubleValue]==0) {
                    d_low=d_close;
                }
                else {
                    d_low=[[pdata objectAtIndex:4] doubleValue];
                }    
                
                NSNumber *close_num=[NSNumber numberWithDouble: d_close ];                        
                NSNumber *open_num=[NSNumber numberWithDouble: d_open ];
                
                NSNumber *high_num=[NSNumber numberWithDouble: d_high ];        
                NSNumber *low_num=[NSNumber numberWithDouble: d_low];
                
               
                
                NSNumber *updown_num=[NSNumber numberWithDouble:  [[pdata objectAtIndex:7] doubleValue]  ];
                NSNumber *updown_p_num=[NSNumber numberWithDouble:  [[pdata objectAtIndex:8] doubleValue] ];
                NSNumber *volume_num=[NSNumber numberWithDouble: [[pdata objectAtIndex:9] doubleValue] ];        
                NSNumber *PE_num=[NSNumber numberWithDouble: [[pdata objectAtIndex:10] doubleValue] ]; 
                NSNumber *MarketCap_num=[NSNumber numberWithDouble:  [[pdata objectAtIndex:11] doubleValue]  ];                  
                
                if ([[pdata objectAtIndex:11] hasSuffix:@"M"]) {
                    NSString *val=[[pdata objectAtIndex:11] stringByReplacingOccurrencesOfString:@"M" withString:@""] ;    
                    float volf=[val doubleValue]*1000000;
                    
                   MarketCap_num=[NSNumber numberWithDouble: volf];             
                } 
                else  if ([[pdata objectAtIndex:11] hasSuffix:@"B"]) {
                    NSString *val=[[pdata objectAtIndex:11] stringByReplacingOccurrencesOfString:@"B" withString:@""] ;    
                    float volf=[val doubleValue]*1000000000;
                    
                    MarketCap_num=[NSNumber numberWithDouble: volf];             
                }                 
                 
                    
                NSNumber *low_52week_num=[NSNumber numberWithDouble: [[pdata objectAtIndex:12] doubleValue] ];
                NSNumber *high_52week_num=[NSNumber numberWithDouble:  [[pdata objectAtIndex:13] doubleValue] ];        
                
                //標記：報價-資料是透過網路上取出報價資料來載入_all 4.yahoo web 資料輸入 
                [tem_dic setObject:code_s forKey:DB_object_sqlite_basic_code];
                [tem_dic setObject:datetime_dt forKey:DB_object_quote_all_datetime];         
                [tem_dic setObject:open_num forKey:DB_object_quote_all_open];
                [tem_dic setObject:close_num forKey:DB_object_quote_all_close];
                [tem_dic setObject:high_num forKey:DB_object_quote_all_high];
                [tem_dic setObject:low_num forKey:DB_object_quote_all_low];
                [tem_dic setObject:updown_num forKey:DB_object_quote_all_updown];
                [tem_dic setObject:updown_p_num forKey:DB_object_quote_all_updown_p];
                [tem_dic setObject:volume_num forKey:DB_object_quote_all_vol];
                [tem_dic setObject:PE_num forKey:DB_object_quote_all_PE];
                [tem_dic setObject:MarketCap_num forKey:DB_object_quote_all_MarketCap];         
                [tem_dic setObject:high_52week_num forKey:DB_object_quote_all_high_52week];   
                [tem_dic setObject:low_52week_num forKey:DB_object_quote_all_low_52week];
                [tem_dic setObject:[NSNumber numberWithDouble: 999 ] forKey:DB_object_quote_all_sample1];                 
                
                
                //2.下面資料是YAHOO 獨有
                //標記：報價-資料是透過網路上取出報價資料來載入_yahoo 4.yahoo web 資料輸入 888               
                {
                    NSString *currency_s=@"";
                    NSString *exchange_s=@"";
                    NSNumber *dividend_rate_num=[NSNumber numberWithDouble: [[pdata objectAtIndex:14] doubleValue] ]; 
                    NSNumber *dividend_yield_num=[NSNumber numberWithDouble: [[pdata objectAtIndex:15] doubleValue] ];       
                    NSNumber *eps_curr_year_num=[NSNumber numberWithDouble:[[pdata objectAtIndex:16] doubleValue]];
                    //下面資料是YAHOO web 沒有                
                    NSNumber *realtime_change_num=[NSNumber numberWithDouble:0 ]; 
                    NSNumber *realtime_chg_percent_num=[NSNumber numberWithDouble: 0];       
                    NSNumber *realtime_price_num=[NSNumber numberWithDouble: 0];
                    NSDate   *realtime_ts=[NSDate dateWithTimeIntervalSince1970:0 ]; 
                    NSNumber *after_mkt_change_num=[NSNumber numberWithDouble: 0 ]; 
                    NSNumber *after_mkt_chg_percent_num=[NSNumber numberWithDouble:0 ];       
                    NSNumber *after_mkt_price_num=[NSNumber numberWithDouble:0 ];
                    
                    [tem_dic setObject:after_mkt_change_num forKey:DB_object_quote_Yahoo_after_mkt_change];   
                    [tem_dic setObject:after_mkt_chg_percent_num forKey:DB_object_quote_Yahoo_after_mkt_chg_percent];
                    [tem_dic setObject:after_mkt_price_num forKey:DB_object_quote_Yahoo_after_mkt_price];             
                    [tem_dic setObject:currency_s forKey:DB_object_quote_Yahoo_currency];   
                    [tem_dic setObject:exchange_s forKey:DB_object_quote_Yahoo_exchange];
                    [tem_dic setObject:dividend_rate_num forKey:DB_object_quote_Yahoo_dividend_rate];               
                    [tem_dic setObject:dividend_yield_num forKey:DB_object_quote_Yahoo_dividend_yield];         
                    [tem_dic setObject:eps_curr_year_num forKey:DB_object_quote_Yahoo_eps_curr_year]; 
                    [tem_dic setObject:realtime_change_num forKey:DB_object_quote_Yahoo_realtime_change];   
                    [tem_dic setObject:realtime_chg_percent_num forKey:DB_object_quote_Yahoo_realtime_chg_percent];
                    [tem_dic setObject:realtime_price_num forKey:DB_object_quote_Yahoo_realtime_price];               
                    [tem_dic setObject:realtime_ts forKey:DB_object_quote_Yahoo_realtime_ts];                
                    [tem_dic setObject:[NSNumber numberWithDouble:888 ] forKey:DB_object_quote_Yahoo_sample1];        
                    
                }
                
                //3.下面資料是bloomberg 獨有
                //標記：報價-資料是透過網路上取出報價資料來載入_bloomberg 4.yahoo web 資料輸入 輸入假的值  111                
                {
                    NSString *introduce=@"";        
                    NSNumber *return_52week_num=[NSNumber numberWithDouble: 0 ];        
                    [tem_dic setObject:introduce forKey:DB_object_quote_Bloomberg_introduce];        
                    [tem_dic setObject:return_52week_num forKey:DB_object_quote_Bloomberg_return_52week];                 
                    [tem_dic setObject:[NSNumber numberWithDouble:111 ] forKey:DB_object_quote_Bloomberg_sample1];         
                    
                    
                
                }
               
                //4.Google特有的資料
                //標記：報價-資料是透過網路上取出報價資料來載入_google 4.yahoo web 資料輸入 輸入假的值111                
                {
                    NSDate *Google_after_mkt_time =[NSDate dateWithTimeIntervalSince1970:9999];       
                    NSNumber *Google_after_mkt_price_num=[NSNumber numberWithDouble: 0 ];         
                    NSNumber *Google_after_mkt_change_num=[NSNumber numberWithDouble: 0 ]; 
                    NSNumber *Google_after_mkt_chg_percent_num=[NSNumber numberWithDouble: 0 ];         
                    NSNumber *Google_shares_num=[NSNumber numberWithDouble: 0 ];         
                    NSNumber *Google_beta_num=[NSNumber numberWithDouble: 0 ]; 
                    NSNumber *Google_institution_own_num=[NSNumber numberWithDouble: 0 ];           
                    NSNumber *Google_delay_num=[NSNumber numberWithDouble: 0 ];         
                    NSNumber *Google_30average_vol_num=[NSNumber numberWithDouble: 0 ]; 
                    NSNumber *Google_timezone=[NSNumber numberWithDouble: 0 ];                 
                    
                    [tem_dic setObject:Google_after_mkt_time forKey:DB_object_quote_Google_after_mkt_time];         
                    [tem_dic setObject:Google_after_mkt_price_num forKey:DB_object_quote_Google_after_mkt_price];  
                    [tem_dic setObject:Google_after_mkt_change_num forKey:DB_object_quote_Google_after_mkt_change];         
                    [tem_dic setObject:Google_after_mkt_chg_percent_num forKey:DB_object_quote_Google_after_mkt_chg_percent];  
                    [tem_dic setObject:Google_shares_num forKey:DB_object_quote_Google_shares];         
                    [tem_dic setObject:Google_beta_num forKey:DB_object_quote_Google_beta];  
                    [tem_dic setObject:Google_institution_own_num forKey:DB_object_quote_Google_institution_own];         
                    [tem_dic setObject:Google_delay_num forKey:DB_object_quote_Google_delay];  
                    [tem_dic setObject:Google_30average_vol_num forKey:DB_object_quote_Google_30average_vol];      
                    [tem_dic setObject:Google_timezone forKey:DB_object_quote_Google_timezone];                
                    [tem_dic setObject:[NSNumber numberWithInt:111] forKey:DB_object_quote_Google_sample1];                 
                }
                                  
                //最後添加到陣列
                [outarray addObject:tem_dic];   
                [tem_dic release];
            }						
            
            
        }
              
        
    }    
    
    //2.將報價資料陣列更新到物件上
    [CommonFunction after_quotefinished_outarray:outarray delgeate:delgeate];   
    
    
    //標記：建立執行緒 4.執行緒內資料計算結束後 要通知delgete    
    [(Data_Model *)delgeate performSelectorOnMainThread:@selector(Quote_Finished:) withObject:outarray waitUntilDone:YES];    
         
    [outarray release];   
        
  
}

-(NSDate *)yahoo_date_time_convert_to_NSDate:(NSString *)dates times:(NSString *)times code:(NSString *)code{
   // NSLog(@"dates=%@ times=%@",dates,times);
   
    NSArray *datearray=    [dates componentsSeparatedByString:@"/"]   ;  
    int year=1990;
    int month=1;
    int day=1;
    
    int hour=0;
    int minute=0;
    
    if ([datearray count]==3) {
        year =[[datearray objectAtIndex:2] intValue];
        month=[[datearray objectAtIndex:0] intValue];   
        day  =[[datearray objectAtIndex:1] intValue];        
    }
    
    //判斷上下午
    if ([times hasSuffix:@"pm"]) {
        //NSLog(@"PM"); 
        NSString *hm=[times stringByReplacingOccurrencesOfString:@"pm" withString:@""];
        NSArray *hma=[hm componentsSeparatedByString:@":"];
        if ([hma count]==2) {
            hour=12+[[hma objectAtIndex:0] intValue];
            minute= [[hma objectAtIndex:1] intValue];                             
        }
        
        
    }
    else if([times hasSuffix:@"am"]){
        //NSLog(@"AM"); 
        NSString *hm=[times stringByReplacingOccurrencesOfString:@"am" withString:@""];
        NSArray *hma=[hm componentsSeparatedByString:@":"];
        if ([hma count]==2) {
            hour= [[hma objectAtIndex:0] intValue];
            minute= [[hma objectAtIndex:1] intValue];                                    
        }                            
        
    }    
    
    
    //NSLog(@"year=%i month=%i day=%i hour=%i minute=%i",year,month,day,hour,minute);
    //轉成 NSDate
    {
        NSCalendar *gregorian=[[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
        //假設yahoo 的資料員都是設定從紐約來的
        [gregorian setTimeZone:[NSTimeZone timeZoneWithName:@"America/New_York"]];
        
        NSDateComponents *timeZoneComps=[[NSDateComponents alloc] init];
        [timeZoneComps setYear:year];
        [timeZoneComps setMonth:month];
        [timeZoneComps setDay:day];
        [timeZoneComps setHour:hour];
        [timeZoneComps setMinute:minute];
        NSDate *date_out=[gregorian dateFromComponents:timeZoneComps];                          
        [gregorian release];
        [timeZoneComps release];            
        
        {//標記: 檢查Yahoo報價日期是否超過目前時間 不合理
            NSTimeZone *TimeZone =[NSTimeZone timeZoneWithName: [self Symbol_converTo_timeZoneWithName:code]];            
            
            
            //下面這段程式是用來調整報價日期超過現在的時間
            NSDate *nowddate;
            nowddate=[NSDate date];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            dateFormatter.dateFormat = @"MMdd";
            [dateFormatter setTimeZone:TimeZone];                              
            
            NSString *nows_time=[dateFormatter stringFromDate:nowddate];
            NSString *quote_time=[dateFormatter stringFromDate:date_out];
            
           // NSLog(@"now_time=%@",nows_time);
          //  NSLog(@"quote_time=%@",quote_time);
            
            if ([quote_time intValue]-[nows_time intValue] >=1) {
                NSTimeInterval seconds = fabs(60.0 * 60.0 * 24.0 * 1.0 * 1);                                    
                date_out=[date_out  dateByAddingTimeInterval: -1 * seconds];                               
                
            }
            [dateFormatter release];
            //下面這段程式是用來調整如果日期是星期六 或是星期日
            
            NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
            [gregorian setTimeZone:TimeZone];                                
            
            
            NSDateComponents *weekdayComponents =
            [gregorian components:NSWeekdayCalendarUnit fromDate:date_out];
            
            NSInteger weekday = [weekdayComponents weekday];
           
            
            //下面的調整方法只是將錯誤的日期往前推到星期五
            if (weekday==7) {
                //如果是星期六
                NSTimeInterval seconds = fabs(60.0 * 60.0 * 24.0 * 1.0 * 1);                                    
                date_out=[date_out  dateByAddingTimeInterval: -1 * seconds];                                     
                
            }
            if (weekday==1) {
                //如果是星期日                                    
                NSTimeInterval seconds = fabs(60.0 * 60.0 * 24.0 * 1.0 * 1);                                    
                date_out=[date_out  dateByAddingTimeInterval: -2 * seconds];                                     
                
            }                                
            
            
            [gregorian release];                                
            
        } 
        
        
        
        
        
        
        return date_out;
    
    
    
    
    
    }
    
    
    
    
    
}


-(NSString *)Symbol_converTo_timeZoneWithName:(NSString*) symbol{
    symbol=[symbol uppercaseString];
    
    NSArray *code_array;
    code_array=[symbol componentsSeparatedByString:@"."];
    //標記:Add Target need Program 時區轉換
    
    
    if ([code_array count]==2) {
        //非美國國家交易所
        if ([[code_array objectAtIndex:1] isEqualToString:@"HK"]) {
            //香港
            return @"Asia/Hong_Kong";
        }
        else if ([[code_array objectAtIndex:1] isEqualToString:@"TW"] || [[code_array objectAtIndex:1] isEqualToString:@"TWO"]){
            //台灣
            return @"Asia/Taipei";
        }   
        else if ([[code_array objectAtIndex:1] isEqualToString:@"AX"]  ){
            //澳洲
            return @"Australia/Sydney";
        } 
        else if ([[code_array objectAtIndex:1] isEqualToString:@"SS"] || [[code_array objectAtIndex:1] isEqualToString:@"SZ"]){
            //中國
            return @"Asia/Shanghai";
        }  
        else if ([[code_array objectAtIndex:1] isEqualToString:@"TO"] || [[code_array objectAtIndex:1] isEqualToString:@"V"]){
            //加拿大
            return @"America/Toronto";
        } 
        else if ([[code_array objectAtIndex:1] isEqualToString:@"BE"] || [[code_array objectAtIndex:1] isEqualToString:@"BM"]  || [[code_array objectAtIndex:1] isEqualToString:@"DU"] || [[code_array objectAtIndex:1] isEqualToString:@"F"]  || [[code_array objectAtIndex:1] isEqualToString:@"HM"] || [[code_array objectAtIndex:1] isEqualToString:@"HA"] || [[code_array objectAtIndex:1] isEqualToString:@"MU"] || [[code_array objectAtIndex:1] isEqualToString:@"SG"] || [[code_array objectAtIndex:1] isEqualToString:@"DE"]  ){
            //德國
            return @"Europe/Berlin";
        }          
        else if ([[code_array objectAtIndex:1] isEqualToString:@"BO"] || [[code_array objectAtIndex:1] isEqualToString:@"NS"]){
            //印度
            return @"Asia/Kolkata";
        }  
        else if ([[code_array objectAtIndex:1] isEqualToString:@"KS"] || [[code_array objectAtIndex:1] isEqualToString:@"KQ"]){
            //韓國
            return @"Asia/Seoul";
        }
        else if ([[code_array objectAtIndex:1] isEqualToString:@"MI"]  ){
            //義大利
            return @"Europe/Rome";
        } 
        else if ([[code_array objectAtIndex:1] isEqualToString:@"NZ"]  ){
            //紐西蘭
            return @"Pacific/Auckland";
        } 
        else if ([[code_array objectAtIndex:1] isEqualToString:@"PA"] || [[code_array objectAtIndex:1] isEqualToString:@"NX"] ){
            //法國
            return @"Europe/Paris";
        }           
        else if ([[code_array objectAtIndex:1] isEqualToString:@"SA"]  ){
            //巴西
            return @"America/Sao_Paulo";
        }         
        else if ([[code_array objectAtIndex:1] isEqualToString:@"MX"]  ){
            //墨西哥
            return @"America/Mexico_City";
        }           
        else if ([[code_array objectAtIndex:1] isEqualToString:@"SI"]  ){
            //新加坡
            return @"Asia/Singapore";
        }          
        else if ([[code_array objectAtIndex:1] isEqualToString:@"L"]  ){
            //英國
            return @"Europe/London";
        }          
        else{
            //如果 都沒有找到設定 就設定為 美國國家交易所
            return @"America/New_York";            
            
        }
    }
    else{
        //美國國家交易所
        return @"America/New_York";
    }
    
}

@end
